//
//  ViewController.m
//  ShangAPP
//
//  Created by macpro on 16/1/21.
//  Copyright © 2016年 wangdao. All rights reserved.
//

#import "ViewController.h"
#import "MyTools.h"
#import "TabBarViewController.h"
#import <AFNetworking.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "JPUSHService.h"
@interface ViewController ()<AMapLocationManagerDelegate>
{
    AMapLocationManager    * _manager;
    UITextField            * _numField;
    UITextField            * _passwordeField;
}


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"denglu_bg.png"]];
    self.navigationItem.title = @"登录";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:20],
       NSForegroundColorAttributeName:UIColorFromRGB(0x444444)}];
    [self.navigationController.navigationBar setBarTintColor:UIColorFromRGB(MYColor)];
    self.navigationController.navigationBar.translucent = NO;
    
    [self viewCreate];
}

-(void)viewCreate
{   //3c1ed8e77fcfcd1f388026c38564fe01
    [AMapLocationServices sharedServices].apiKey =@"3c1ed8e77fcfcd1f388026c38564fe01";
    _manager = [[AMapLocationManager alloc]init];
    _manager.delegate = self;
    _manager.desiredAccuracy=kCLLocationAccuracyBest;
    [_manager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
// 带逆地理（返回坐标和地址信息）
    [_manager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
        }
        if (regeocode)
        {
            long y = regeocode.formattedAddress.length;
            for (int i = 0; i<10; i++) {
                NSRange range = [regeocode.formattedAddress rangeOfString:[NSString stringWithFormat:@"%d",i]];
                if (y > range.location) {
                    y = range.location;
                }
            }
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:[NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude] forKey:@"coordinate"];
            
            if (regeocode.city) {
                [user setObject:[NSString stringWithFormat:@"%@",regeocode.city] forKey:@"city"];
            }else{
                [user setObject:[NSString stringWithFormat:@"%@",regeocode.province] forKey:@"city"];
            }
            
            [user synchronize];
            
        }
    }];
    
    UIView * navView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    navView.backgroundColor =UIColorFromRGB(MYColor);
    [self.view addSubview:navView];
    
    UILabel * labelName =[[UILabel alloc]initWithFrame:CGRectMake(0, 23, WIDTH, 40)];
    labelName.textAlignment =NSTextAlignmentCenter;
    labelName.text =@"邢少爷";
    labelName.font =[UIFont systemFontOfSize:20];
    [navView addSubview:labelName];
    
    
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64)];
    imageview.image = [UIImage imageNamed:@"denglu_bg"];
    [self.view addSubview:imageview];
    UIButton *backbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    [backbtn addTarget:self action:@selector(textback) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:backbtn atIndex:0];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
    
    
    _numField = [[UITextField alloc]initWithFrame:CGRectMake(70, 140 * MYHEIGHT, WIDTH - 120, 50 * MYHEIGHT)];
    [_numField setBorderStyle:UITextBorderStyleNone];
    _numField.placeholder = @"手机号码";
    _numField.font = [UIFont systemFontOfSize:15];
    _numField.textColor = UIColorFromRGB(0x333333);
    [self.view addSubview:_numField];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(20, 195 * MYHEIGHT, WIDTH - 40, 1)];
    line1.backgroundColor = UIColorFromRGB(0xcecece);
    [self.view addSubview:line1];
    UIImageView *numImage1 = [[UIImageView alloc]initWithFrame:CGRectMake(20, 150 * MYHEIGHT, 35 * MYHEIGHT, 35 * MYHEIGHT)];
    numImage1.image = [UIImage imageNamed:@"phonenum"];
    [self.view addSubview:numImage1];
    
    
    
    _passwordeField = [[UITextField alloc]initWithFrame:CGRectMake(70, 200 * MYHEIGHT, WIDTH - 120, 50 * MYHEIGHT)];
    [_passwordeField setBorderStyle:UITextBorderStyleNone];
    _passwordeField.placeholder = @"输入密码";
    _passwordeField.secureTextEntry = YES;
    _passwordeField.font = [UIFont systemFontOfSize:15];
    _passwordeField.textColor = UIColorFromRGB(0x333333);
    [self.view addSubview:_passwordeField];
    
    UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(20, 255 * MYHEIGHT, WIDTH - 40, 1)];
    line2.backgroundColor = UIColorFromRGB(0xcecece);
    [self.view addSubview:line2];
    UIImageView *numImage2 = [[UIImageView alloc]initWithFrame:CGRectMake(20, 210 * MYHEIGHT, 35 * MYHEIGHT, 35 * MYHEIGHT)];
    numImage2.image = [UIImage imageNamed:@"passworde"];
    [self.view addSubview:numImage2];
    
    
    UIButton *loginbtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH/2 - 130 * MYHEIGHT, 340 * MYHEIGHT, 260 * MYHEIGHT, 40 * MYHEIGHT)];
    loginbtn.backgroundColor = UIColorFromRGB(0x1DE3DD);
    loginbtn.layer.cornerRadius = 20 * MYHEIGHT;
    [loginbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginbtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginbtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginbtn];
    
}
//登录
-(void)login
{
    if (_numField.text.length == 0) {
        [self.view makeToast:@"请填写手机号" duration:1.0 position:CSToastPositionCenter];
    }else if (_passwordeField.text.length == 0){
        [self.view makeToast:@"请填写密码" duration:1.0 position:CSToastPositionCenter];
    }else{
        
        NSString *url = @"http://www.xsy777.com/app/user/login.html";
        NSDictionary *dic1 = @{@"mobile":_numField.text,
                               @"password":_passwordeField.text,
                               @"group":@"4"};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
        
        [manager POST:url parameters:dic1 success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            if ([[responseObject objectForKey:@"status"] intValue] == 1) {
                
                [self.view makeToast:@"登录成功" duration:1.0 position:CSToastPositionCenter];
                
                NSDictionary *dic2 = [[NSDictionary alloc]initWithDictionary:[responseObject objectForKey:@"data"]];
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
                [user setObject:_passwordeField.text forKey:@"password"];
                [user setObject:[dic2 objectForKey:@"user_token"] forKey:@"token"];
                
                if ([[dic2 objectForKey:@"sex"] intValue] == 0) {
                    [user setObject:@"保密" forKey:@"sex"];
                }else if ([[dic2 objectForKey:@"sex"] intValue] == 1){
                    [user setObject:@"男" forKey:@"sex"];
                }else if ([[dic2 objectForKey:@"sex"] intValue] == 2){
                    [user setObject:@"女" forKey:@"sex"];
                }
                [self joinJPush:[dic2 objectForKey:@"uid"]];
                [user synchronize];
                
                CATransition*ani=[CATransition animation];
                
                ani.type=@"push";
                ani.duration=0.5;
                ani.subtype=kCATransitionFromRight;
                
                TabBarViewController*vc=[[TabBarViewController alloc]init];
                [self.navigationController.view.layer addAnimation:ani forKey:nil];
                //[self.navigationController pushViewController:vc animated:YES];
                [self presentViewController:vc animated:YES completion:nil];
                
            }else if ([[responseObject objectForKey:@"status"] intValue] == 0){
                [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if ([MyTools connectedToNetwork] == 0) {
                [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
            }else{
                [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
            }
        }];
    }
}

#pragma mark 用户+标签、别名
-(void)joinJPush:(NSString *)uid{
    
    [JPUSHService setTags:nil alias:uid fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags , iAlias);
    }];
}

-(void)textback
{
    [_numField resignFirstResponder];
    [_passwordeField resignFirstResponder];
}

//页面即将出现
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationItem setHidesBackButton:YES];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user objectForKey:@"token"];
    if (token.length == 0) {
        
    }else{
        TabBarViewController*vc=[[TabBarViewController alloc]init];
        [self.navigationController pushViewController:vc animated:NO];
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
